using System;
using System.Data;
using System.Configuration;
using System.Web;		 
using System.Drawing;    

namespace Possan.Graphics.Filters
{							    
	public class RoundCorners : IBaseFilter
	{
		public int Radius;
		public string Color;
		public string Corners;

		public string ParameterDefinition
		{
			get
			{
				     return null;
			}
		}

		public RoundCorners()
		{
			Radius = 0;
			Color = "";
			Corners = "tl,tr,br,bl";
		}

		public Bitmap Filter(Bitmap bitmap)
		{
			int w = bitmap.Width;
			int h = bitmap.Height;

		//	if (Corners == null || Corners == "")
		//		Corners = "tl,tr,bl,br";

			Corners = Corners.ToLower();

			Bitmap bmp2 = new Bitmap(w, h);
			bmp2.SetResolution(bitmap.HorizontalResolution, bitmap.VerticalResolution);
			System.Drawing.Graphics g2 = System.Drawing.Graphics.FromImage(bmp2);

			Bitmap mask = new Bitmap(w, h);
			mask.SetResolution(bitmap.HorizontalResolution, bitmap.VerticalResolution);
			System.Drawing.Graphics mg = System.Drawing.Graphics.FromImage(mask);

			mg.FillRectangle(new SolidBrush(System.Drawing.Color.White), new Rectangle(0, 0, w, h));

			mg.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bicubic;
			mg.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

			float fr = (float)Radius * 2;

			PointF[] pts1 = new PointF[21];
			PointF[] pts2 = new PointF[21];
			PointF[] pts3 = new PointF[21];
			PointF[] pts4 = new PointF[21];

			pts1[0] = new PointF(-1, -1);
			pts2[0] = new PointF(w, -1);
			pts3[0] = new PointF(w, h);
			pts4[0] = new PointF(-1, h);
			for (int j = 0; j < 20 ;  j++)
			{
				float a = 270.0f - (90.0f * ((float)j / 20.0f));
				float r = a * (float)Math.PI / 180.0f;
				float x = 0 + fr + fr * (float)Math.Cos(r);
				float y = 0 + fr + fr * (float)Math.Sin(r);
				pts1[j + 1] = new PointF(x - 1, y - 1);
				pts2[j + 1] = new PointF(w - x, y - 1);
				pts3[j + 1] = new PointF(w - x, h - y);
				pts4[j + 1] = new PointF(x - 1, h - y);
			}

			if (Corners.Contains("tl")) mg.FillClosedCurve(new SolidBrush(System.Drawing.Color.Black), pts1);
			if (Corners.Contains("tr")) mg.FillClosedCurve(new SolidBrush(System.Drawing.Color.Black), pts2);
			if (Corners.Contains("br")) mg.FillClosedCurve(new SolidBrush(System.Drawing.Color.Black), pts3);
			if (Corners.Contains("bl")) mg.FillClosedCurve(new SolidBrush(System.Drawing.Color.Black), pts4);

			// Copy alpha from buffer

			for (int v = 0; v < h ;  v++)
			{
				for (int u = 0; u < w ;  u++)
				{
					Color oldcolor = bitmap.GetPixel(u, v);
					Color oldmask = mask.GetPixel(u, v);
					int newalpha = (oldcolor.A * oldmask.R) / 256;
					Color newcolor = System.Drawing.Color.FromArgb(newalpha, oldcolor);
					bmp2.SetPixel(u, v, newcolor);
				}
			}
			     return bmp2;
		}			   
	}
}





